package service.impl;

import dbconnection.ConnectionFactory;
import service.House;

import java.sql.*;
import java.util.ArrayList;

import common.Split;

/**
 * Created by Administrator on 2016/12/15.
 */
public class HouseImpl implements House{

    public String houseInit() throws Exception {
        ConnectionFactory connectionFactory=new ConnectionFactory();
        Connection connection=connectionFactory.getConnection();
        ArrayList<String> arrayList=new ArrayList<String>();
        String sql="select houseName,price,inventory from jc_house";
        PreparedStatement preparedStatement;
        preparedStatement=(PreparedStatement)connection.prepareStatement(sql);
        ResultSet resultSet=preparedStatement.executeQuery();
        while(resultSet.next()){
            arrayList.add(resultSet.getString("houseName"));
            arrayList.add(resultSet.getInt("price")+"");
            arrayList.add(resultSet.getInt("inventory")+"");
        }
        String init="";
        for(int i=0;i<arrayList.size();i++){
            init+=arrayList.get(i);
            if(i!=arrayList.size()-1)
                init+=",";
        }
//        System.out.println(init);
        connection.close();
        return init;//出租屋,0,100,北师大青年公寓,40,110,二手京师家园小三房,120,120,格力香樟,125,125,龙光海悦云天复式,500,135,情侣路边无敌海景大房,1000,150,野狸岛边小岛独栋别墅,5000,160
    }

    public String houseHav(int userId) throws Exception {
        ConnectionFactory connectionFactory=new ConnectionFactory();
        Connection connection=connectionFactory.getConnection();
        ArrayList<String> nameList=new ArrayList<String>();
        ArrayList<String> priceList=new ArrayList<>();
        String sql="select houseName,inventory from jc_house";
        PreparedStatement preparedStatement;
        preparedStatement=(PreparedStatement)connection.prepareStatement(sql);
        ResultSet resultSet=preparedStatement.executeQuery();
        while(resultSet.next()){
            nameList.add(resultSet.getString("houseName"));
            nameList.add(resultSet.getInt("inventory")+"");
        }
        sql="select housePrice from jc_userproperty where userId=?";
        preparedStatement=(PreparedStatement)connection.prepareStatement(sql);
        preparedStatement.setInt(1,userId);
        resultSet=preparedStatement.executeQuery();
        String housePri="";
        while(resultSet.next()){
            housePri=resultSet.getString("housePrice");
        }
        Split split=new Split();
        priceList=split.splitList(housePri);

        String have="";
        int j=0;
        for(int i=0;i<nameList.size();i++){
            if(i%2==0){
                have+=nameList.get(i)+","+priceList.get(j);
                j++;
                if(i!=nameList.size()-1)
                    have+=",";
            }else{
                have+=nameList.get(i)+",";
            }
        }
        connection.close();
        return have;
    }

}